<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="申请者" prop="createBy">
          <el-input v-model="queryParams.createBy" placeholder="请输入申请者" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="日期范围" prop="times1">
          <el-date-picker type="daterange" v-model="queryParams.times1" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
            :style="{ width: '100%' }" start-placeholder="开始日期" end-placeholder="结束日期"
            range-separator="至"></el-date-picker>
        </el-form-item>
        <el-form-item label="是否批准" prop="borrowingStatus">
          <el-select v-model="queryParams.borrowingStatus" placeholder="请选择是否批准" clearable>
            <el-option v-for="dict in borrowing_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery" @change="timesChange()">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-row>

    <el-row>
      <el-form-item label="借支总额筛选" prop="times2">
        <el-date-picker type="daterange" v-model="queryParams.times2" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
          :style="{ width: '100%' }" start-placeholder="开始日期" end-placeholder="结束日期"
          range-separator="至"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="amount">查询</el-button>
      </el-form-item>
    </el-row>
    <el-statistic group-separator="," :precision="2" :value="data.queryParams.ca" title="所有借支金额/元"></el-statistic>

    <el-divider />


    <el-table v-loading="loading" :data="borrowingLogList" @selection-change="handleSelectionChange">
      <el-table-column label="借支记录id" align="center" prop="borrowingLogId" />
      <el-table-column label="申请者" align="center" prop="createBy">
        <template #default="scope">
          <el-button style="background-color: #5080e7; color: white; border: 1px solid #5080e7;" link
            @click="showUser(scope.row)">{{ scope.row.createBy }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="借支金额" align="center" prop="borrowingLogAmount" />
      <el-table-column label="借支理由" align="center">

        <template #default="scope">
          <span v-if="scope.row.reason.length > 6">
            <el-button link @click="showReason(scope.row)">{{ scope.row.reason.substring(0, 6) }}.......</el-button>
          </span>
          <span v-else>
            {{ scope.row.reason }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="发起时间" align="center" prop="createTime" width="180">

        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="通过时间" align="center" prop="updateTime" width="180">

        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="borrowingStatus">

        <template #default="scope">
          <dict-tag :options="borrowing_status" :value="scope.row.borrowingStatus" />
        </template>
      </el-table-column>

      <el-table-column label="操作" class-name="small-padding" prop="borrowingStatus" width="250" align="center">

        <template #default="scope">
          <el-form ref="borrowingLogRef" :model="form" :rules="rules" label-width="80px">
            <el-row>
              <el-col :span=12>
                <el-button link type="primary" @click="handleUpdate(scope.row, 1)"
                  v-hasPermi="['manage:borrowingLog:edit']">批 准</el-button>
              </el-col>
              <el-col :span=12>
                <el-button link type="primary" @click="handleUpdate(scope.row, 2)"
                  v-hasPermi="['manage:borrowingLog:edit']">不批准</el-button>
              </el-col>
            </el-row>
          </el-form>
        </template>

      </el-table-column>
    </el-table>

    <el-dialog :title="title" v-model="open" width="500px" append-to-body @close="reset">
      <div class="center-content">
        <el-form ref="borrowingLogRef" :model="form" :rules="rules" label-width="80px">
          {{ form.reason }}
          {{ form.borrowedAmount }}
        </el-form>
      </div>
    </el-dialog>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

  </div>
</template>

<script setup name="BorrowingLog">
import { listBorrowingLog, countAmount, updateBorrowingLog } from "@/api/manage/borrowingLog";
import { getBorrowing } from "@/api/manage/borrowing";

import { computed, ref } from "vue";

const { proxy } = getCurrentInstance();
const { borrowing_status } = proxy.useDict('borrowing_status');

const borrowingLogList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    createBy: null,
    createTime: null,
    borrowingStatus: null,
    times1: [],
    times2: [],
    ca: 0
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询查询借支记录列表 */
function getList() {
  loading.value = true;
  listBorrowingLog(queryParams.value).then(response => {
    borrowingLogList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function getCurrentDateFormatted(val) {
  const now = new Date(val);
  const year = now.getFullYear();
  const month = ('0' + (now.getMonth() + 1)).slice(-2);
  const day = ('0' + now.getDate()).slice(-2);

  return `${year}-${month}-${day}`;
}

function getCurrentDateFormattedNow() {
  const now = new Date();
  const year = now.getFullYear();
  const month = ('0' + (now.getMonth() + 1)).slice(-2);
  const day = ('0' + now.getDate()).slice(-2);

  return `${year}-${month}-${day}`;
}
function amount() {
  if (data.queryParams.times2.length == 0) {
    data.queryParams.times2[0] = getCurrentDateFormatted(2024, 1, 1);
    data.queryParams.times2[1] = getCurrentDateFormattedNow() + 1;
  }
  console.log(queryParams.value);
  countAmount(queryParams.value).then(response => {
    // console.log(response.msg);
    data.queryParams.ca = response.msg;
  });
}

// 表单重置
function reset() {
  form.value = {
    userId: null,
    borrowingLogId: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    borrowingStatus: null,
    times1: [],
    times2: [],
    borrowingLogAmount: null,
  };
  proxy.resetForm("borrowingLogRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.times1 = [];
  queryParams.times2 = [];
  queryParams.startTime = null;
  queryParams.endTime = null;
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.borrowingLogId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 查看某用户借支总额 */
function showUser(row) {
  getBorrowing(row.userId).then(response => {
    form.value.borrowedAmount = row.createBy + "：" + response.data.borrowedAmount + "元"
    open.value = true;
    title.value = "用户借支总额";
  });

}

/** 查看详细借支理由 */
function showReason(row) {
  form.value.reason = "借支理由：" + row.reason
  open.value = true;
  title.value = "详细借支理由";
}

/** 修改按钮操作 */
function handleUpdate(row, status) {
  const _borrowingLogId = row.borrowingLogId || ids.value
  proxy.$modal.confirm('是否确认本次操作？').then(function () {
    form.value = row
    form.value.borrowingLogId = _borrowingLogId;
    form.value.borrowingStatus = status;
    return updateBorrowingLog(form.value);
  }).then(() => {
    proxy.$modal.msgSuccess("修改成功");
    getList()
  }).catch(() => { getList() })
}

amount()
getList();
</script>

<style scoped>
.center-content {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style>